<template>
  <div class="upload-container">
    <el-upload
      ref="upload"
      v-bind="$attrs"
      :action="action"
      :on-success="handleSuccess"
      :on-error="handleError" 
      :limit="limit"
      :before-upload="beforeUpload"
      :show-file-list="showFileList" 
      :accept="accept" 
      :data="{type: type, imageheight: imgH, imagewidth: imgW}"
      v-on="$listeners">
      <div class="upload-buttons" :style="{'width': width + 'px', 'height': height + 'px', 'flex-direction': direction}" v-if="showUploadBtn">
        <div><el-button slot="trigger" size="small" type="primary" :loading="loading">本地上传</el-button></div>
        <div><el-button size="small" type="primary" @click.stop="showDrawer = !showDrawer">图库选择</el-button></div> 
      </div>
    </el-upload>
    <div class="image-list" :style="{'width': width + 'px', 'height': height + 'px'}" v-for="(image, idx) in imageList" :key="image">
      <el-image style="width: 100%; height: 100%;" :src="image | formatImage" :preview-src-list="imageList" fit="cover"></el-image>
      <el-button class="del" @click="delImage(idx)">删除</el-button>
    </div>
    <Drawer v-show="showDrawer" :isMulti="limit > 1 ? true : false" :type="type" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
  </div>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
export default {
  components: {
    Drawer
  },
  filters: {
    formatImage(image) {
      if(image && image.indexOf('http') > -1) {
        return image
      } else {
        return this.utils.setCdnUrl() + image
      }
    }
  },
  props: {
    action: {
      type: String,
      default: '/api/api/general/upload'
    },
    type: {
      type: String,
      default: 'product_comment'
    },
    showFileList: {
      type: Boolean,
      default() {
        return false
      }
    },
    direction: {
      type: String,
      default: 'column'
    },
    limit: {
      type: Number
    },
    width: {
      type: [Number, String],
      default() {
        return 200
      }
    },
    height: {
      type: [Number, String],
      default() {
        return 200
      }
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png'
    },
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    fileMaxSize: {
      type: Number,
      default() {
        return 1024000
      }
    },
    square: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  computed: {
    showUploadBtn() {
      if(this.limit && this.limit > 0) {
        return this.imageList.length < this.limit
      } else {
        return true
      }
    },
    accepts() {
      return this.accept.replace(/\./g, '').split(',')
    }
  },
  data() {
    return {
      imgH: '',
      imgW: '',
      imageList: this.fileList.filter(item => item).map(item => {
        return this.formatImage(item)
      }),
      showDrawer: false
    }
  },
  watch: {
    fileList(array) {
      this.imageList = array.filter(item => item).map(item => {
        return this.formatImage(item)
      })
    }
  },
  beforeDestroy() {
    this.$refs.upload.clearFiles()
  },
  methods: {
    formatImage(image) {
      if(image && image.indexOf('http') > -1) {
        return image
      } else {
        return this.utils.setCdnUrl() + image
      }
    },
    delImage (index) {
      let file = this.imageList.splice(index, 1)
      this.$emit('update:fileList', this.imageList)
      this.$emit('delete', file, this.imageList)
      this.$refs.upload.clearFiles()
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (Array.isArray(data) && data.length > 0) { 
        for(let i = 0; i < data.length; i++) {
          if(this.accepts.includes(data[i].imagetype)) {
            this.imageList.push(data[i].tem_url)
            this.$emit('update:fileList', this.imageList)
            this.$emit('success', {
              filePathName: data[i].tem_url
            })
          } else {
            this.$message.error("只能上传≤1M的" + this.accept + "格式的图片；图片"+ data[i].filename +'不符合要求')
          }

        }
      } else if(data && data.filePathNameHttp) {
        this.imageList.push(data.filePathNameHttp)
        this.$emit('update:fileList', this.imageList)
        this.$emit('success', data)
      }
      // console.log(this.imageList)
    },
    getImageInfo(file) {
      return new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = true
          valid ? resolve(img) : reject();
        }
        img.src = _URL.createObjectURL(file);
      })
    },
    beforeUpload(file){
      if(!this.accepts.includes(file.type.replace('image/', ''))){
        this.$message.error("仅支持" + this.accept + "格式的图片")
        return false
      }
      if (file.size > this.fileMaxSize) {
        this.$message.error("只能上传≤1M的" + this.accept + "格式的图片；图片"+ file.name +'不符合要求')
        return false
      }
      this.getImageInfo(file).then(img => {
        if(img.width !== img.height && this.square) {
          this.$message.error("仅支持尺寸为1:1的图片")
          return false
        }
        this.imgW = img.width
        this.imgH = img.height
      })
      this.loading = true
    },
    handleError(){
      this.$message.error('上传图标失败')   
      this.loading = false
    },
    handleSuccess (response) {
      this.imageList.push(response.data.filePathNameHttp)
      this.$emit('update:fileList', this.imageList)
      this.$emit('success', response.data)
      this.loading = false
      // this.$message.success('上传图片成功')   
    }
  }
}
</script>

<style scoped>
  .upload-container {
    display: flex;
    flex-wrap: wrap;
  }
  .upload-buttons {
    display: flex;
    width: 200px;
    height: 200px;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border: 1px dashed #ccc;
    border-radius: 5px;
    margin-right: 10px;
  }
  .upload-buttons > div {
    margin: 6px 10px;
  }
  .upload-container .image-list {
    flex-shrink: 1;
    position: relative;
    width: 200px;
    height: 200px;
    border-radius: 5px;
    margin-right: 10px;
    /* margin-bottom: 10px; */
    border: 1px dashed #ccc;
    border-radius: 5px;
  }
  .upload-container .image-list .del {
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 9;
  }
</style>